const _ = require("underscore")

class Util {
  constructor() {
    wx.setInnerAudioOption({
      mixWithOther: true,
      obeyMuteSwitch: false,
    })
  }

  //返回日期字串 格式为YYYY/MM/DD HH:mi:SS
  formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
  }
  formatDate(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(this.formatNumber).join('.')
  }
  formatTime(date) {
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [hour, minute, second].map(this.formatNumber).join(':')
  }
  getDateDiff(dateTimeStamp) {
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
      return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    var result
    if (monthC >= 1) {
      result = "" + parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
      result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else
      result = "刚刚";
    return result;
  }

  //日期格式化
  formatDateString(formatStr, fdate) {
    if (fdate) {
      if (~fdate.indexOf('.')) {
        fdate = fdate.substring(0, fdate.indexOf('.'));
      }
      fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
      var fTime, fStr = 'ymdhis';
      if (!formatStr)
        formatStr = "y-m-d h:i:s";
      if (fdate)
        fTime = new Date(fdate);
      else
        fTime = new Date();
      var month = fTime.getMonth() + 1;
      var day = fTime.getDate();
      var hours = fTime.getHours();
      var minu = fTime.getMinutes();
      var second = fTime.getSeconds();
      month = month < 10 ? '0' + month : month;
      day = day < 10 ? '0' + day : day;
      hours = hours < 10 ? ('0' + hours) : hours;
      minu = minu < 10 ? '0' + minu : minu;
      second = second < 10 ? '0' + second : second;
      var formatArr = [
        fTime.getFullYear().toString(),
        month.toString(),
        day.toString(),
        hours.toString(),
        minu.toString(),
        second.toString()
      ]
      if (formatStr == '年月日') {
        formatStr = formatArr[0] + "年" + formatArr[1] + "月" + formatArr[2] + "日"
      } else {
        for (var i = 0; i < formatArr.length; i++) {
          formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
        }
      }

      return formatStr;
    } else {
      return "";
    }
  }
  //clipboard
  async setClipboardData(data) {
    return new Promise((resolve, reject) => {
      wx.setClipboardData({
        data: data,
        success: resolve,
        fail: reject
      })
    })
  }
  async getClipboardData() {
    return new Promise((resolve, reject) => {
      wx.getClipboardData({
        success: (res) => resolve(res.data),
        fail: reject
      })
    })
  }
  //交互
  async showLoading(title, timeout = 10000) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        wx.hideLoading()
      }, timeout)
      wx.showLoading({
        title: title,
        success: resolve,
        fail: reject
      })
    })
  }
  async hideLoading() {
    wx.hideLoading()
  }
  async showToast(title, duration = 1500) {
    wx.showToast({
      title,
      duration
    })
  }
  async showModal(title, content,showCancel,confirmText) {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: title,
        content: content,
        showCancel:showCancel,
        confirmText:confirmText||'确定',
        success: (res) => {
          if (res.confirm) {
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail: reject
      })
    })
  }
  async showActionSheet(itemList) {
    return new Promise((resolve, reject) => {
      wx.showActionSheet({
        itemList: itemList,
        success: (res) => {
          resolve(res.tapIndex)
        },
        fail: (res) => {
          reject(res.errMsg)
        }
      })
    })
  }
  //扫描条形码或二维码
  async scanCode(onlyFromCamera = false) {
    return new Promise((resolve, reject) => {
      wx.scanCode({
        onlyFromCamera: onlyFromCamera,
        success: resolve,
        fail: reject
      })
    })
  }
  async takePhoto() {
    console.log("takePhoto is begin")
    return new Promise((resolve, reject) => {
      const ctx = wx.createCameraContext()
      console.log("ctx:", ctx)
      ctx.takePhoto({
        quality: 'high',
        success: resolve,
        fail: reject
      })
    })
  }
  async chooseImage(isCompressed) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1,
        sizeType: isCompressed ? ['compressed'] : ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: resolve,
        fail: reject
      })
    })
  }
  //file
  async readFile(option) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: option.filePath,
        encoding: option.encoding, //ascii,base64,binary,utf-8
        success: resolve,
        fail: reject
      })
    })
  }
  async writeFile(option) {
    return new Promise((resolve, reject) => {
      wx.FileSystemManager().writeFile({
        filePath: option.filePath,
        data: option.data,
        encoding: option.encoding, //ascii,base64,binary,utf-8
        success: resolve,
        fail: reject
      })
    })
  }
  async rmFile(option) {
    return new Promise((resolve, reject) => {
      wx.FileSystemManager().unlinkFile({
        filePath: option.filePath,
        success: resolve,
        fail: reject
      })
    })
  }
  //storage
  async setStorage(key, value) {
    return new Promise((resolve, reject) => {
      try {
        let data = JSON.stringify(value)
        wx.setStorage({
          key: key,
          data: data,
          success: resolve,
          fail: reject
        })
      } catch (e) {
        reject(e)
      }
    })
  }
  async getStorage(key) {
    return new Promise((resolve, reject) => {
      try {
        wx.getStorage({
          key: key,
          success: (res) => {
            if (typeof (res.data) != "undefined") {
              console.log(JSON.stringify(res.data))

              resolve(JSON.parse(res.data))
            } else {
              resolve(null)
            }

          },
          fail: reject
        })
      } catch (e) {
        reject(e)
      }
    })
  }
  setStorageSync(key, data) {
    data = wx.setStorageSync({
      key: key,
      data: JSON.stringify(data)
    })
  }
  getStorageSync(key) {
    let data = wx.getStorageSync(key)
    return JSON.parse(data || null)
  }
  async getStorageInfo() {
    return new Promise((resolve, reject) => {
      wx.getStorageInfo({
        success: (res) => resolve(res),
        fail: reject
      })
    })
  }
  async clearStorageInfo() {
    return new Promise((resolve, reject) => {
      wx.clearStorageInfo({
        success: (res) => resolve(res),
        fail: reject
      })
    })
  }
  async removeStorage(key) {
    return new Promise((resolve, reject) => {
      wx.removeStorage({
        key: key,
        success: resolve,
        fail: reject
      })
    })
  }

  //获取网络数据
  async request(option) {
    this.showLoading("加载数据")
    return new Promise((resolve, reject) => {
      wx.request({
        url: option.url,
        method: option.method,
        header: option.header,
        data: option.data || {},
        success: resolve,
        fail: error => {
          this.showToast("网络链接失败")
          this.hideLoading()
          reject(error)
        },
        complete: this.hideLoading
      })
    })
  }
  async downloadFile(option, pgComponent, key) {
    //pgComponent是一个progress组件，key为该组件反应进度指标（0-100）的值
    return new Promise((resolve, reject) => {
      var task = wx.downloadFile({
        url: option.url,
        filePath: option.filePath,
        success: resolve,
        failt: reject
      })
      if (!pgComponent) return
      task.onProgressUpdate((res) => {
        pgComponent.setData({
          show: true,
          [key]: res.progress
        })
        if (res.progress == 100) {
          setTimeout(() => {
            pgComponent.setData({
              show: false,
              [key]: 0
            })
          }, 500)
        }
      })
    })
  }
  async uploadFile(option, pgComponent, key) {
    //pgComponent是一个progress组件，key为该组件反应进度指标（0-100）的值
    return new Promise((resolve, reject) => {
      var task = wx.uploadFile({
        url: option.url,
        filePath: option.filePath,
        header: {
          "content-type": "multipart/form-data"
        },
        name: option.name,
        formData: option.formData,
        success: resolve,
        failt: reject
      })
      if (!pgComponent) return
      task.onProgressUpdate((res) => {
        pgComponent.setData({
          show: true,
          [key]: res.progress
        })
        if (res.progress == 100) {
          setTimeout(() => {
            pgComponent.setData({
              show: false,
              [key]: 0
            })
          }, 500)
        }
      })
    })
  }
  //中英文互译

  //语音合成播放
 
}

const util = new Util()

class Map {
  constructor(id) {
    this.ctx = wx.createMapContext(id, this)
  }
  async moveTo(option = {}) {
    return new Promise((resolve, reject) => {
      this.ctx.moveToLocation({
        longitude: option.longitude || null,
        latitude: option.latitude || null,
        success: resolve,
        fail: reject
      })
    })
  }
  async getLocation(option = {}) {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: option.type,
        success: resolve,
        fail: reject
      })
    })
  }
  async startUpdate(option = {
    background: true,
    onChange: null
  }) {
    return new Promise((resolve, reject) => {
      if (option.background) {
        wx.startLocationUpdateBackground({
          success: (res) => {
            wx.onLocationChange(option.onChange)
            resolve(res)
          },
          fail: reject
        })
      } else {
        wx.startLocationUpdate({
          success: (res) => {
            wx.onLocationChange(option.onChange)
            resolve(res)
          },
          fail: reject
        })
      }
    })
  }
  async stopUpdate() {
    return new Promise((resolve, reject) => {
      wx.stopLocationUpdate({
        success: (res) => {
          wx.offLocationChange(null)
          resolve(res)
        },
        fail: reject
      })
    })
  }
}



module.exports = {
  util: util,
  Map: Map,
}